<?php


namespace App\Server;

use \App\Models\Weather;

/**
 * 天气指数
 * Class WeatherIndex
 * @package App\Server
 */
class WeatherIndex
{
    public static $city = [
        'nankang' => [
            'name'      => '南康',
            'moji'      => 'https://tianqi.moji.com/fish/china/jiangxi/nankang-district',
            'moji_wind' => 'https://tianqi.moji.com/weather/china/jiangxi/nankang-district',
            'pressure_today' => 'https://tianqi.2345.com/nankang1d/60504.htm',
            'pressure_tomorrow' => 'https://tianqi.2345.com/nankang2d/60504.htm',
        ],
        'xinfeng' => [
            'name'      => '信丰',
            'moji'      => 'https://tianqi.moji.com/fish/china/jiangxi/xinfeng-county',
            'moji_wind' => 'https://tianqi.moji.com/weather/china/jiangxi/xinfeng-county',
            'pressure_today' => 'https://tianqi.2345.com/xinfeng1d/60943.htm',
            'pressure_tomorrow' => 'https://tianqi.2345.com/xinfeng2d/60943.htm',
        ],
        'ganxian' => [
            'name'      => '赣县',
            'moji'      => 'https://tianqi.moji.com/fish/china/jiangxi/ganxian-district',
            'moji_wind' => 'https://tianqi.moji.com/weather/china/jiangxi/ganxian-district',
            'pressure_today' => 'https://tianqi.2345.com/ganxian1d/71399.htm',
            'pressure_tomorrow' => 'https://tianqi.2345.com/ganxian2d/71399.htm',
        ],
        'zhangong' => [
            'name'      => '章贡',
            'moji'      => 'https://tianqi.moji.com/fish/china/jiangxi/zhanggong-district',
            'moji_wind' => 'https://tianqi.moji.com/weather/china/jiangxi/zhanggong-district',
            'pressure_today' => 'https://tianqi.2345.com/zhanggong1d/71945.htm',
            'pressure_tomorrow' => 'https://tianqi.2345.com/zhanggong2d/71945.htm',
        ],
        'yudu' => [
            'name'      => '于都',
            'moji'      => 'https://tianqi.moji.com/fish/china/jiangxi/yudu-county',
            'moji_wind' => 'https://tianqi.moji.com/weather/china/jiangxi/yudu-county',
            'pressure_today' => 'https://tianqi.2345.com/yudu1d/60506.htm',
            'pressure_tomorrow' => 'https://tianqi.2345.com/yudu2d/60506.htm',
        ],
        'ningdu' => [
            'name'      => '宁都',
            'moji'      => 'https://tianqi.moji.com/fish/china/jiangxi/ningdu-county',
            'moji_wind' => 'https://tianqi.moji.com/weather/china/jiangxi/ningdu-county',
            'pressure_today' => 'https://tianqi.2345.com/ningdu1d/60905.htm',
            'pressure_tomorrow' => 'https://tianqi.2345.com/ningdu2d/60905.htm',
        ],
        'shangyou' => [
            'name'      => '上犹',
            'moji'      => 'https://tianqi.moji.com/fish/china/jiangxi/shangyou-county',
            'moji_wind' => 'https://tianqi.moji.com/weather/china/jiangxi/shangyou-county',
            'pressure_today' => 'https://tianqi.2345.com/shangyou1d/70483.htm',
            'pressure_tomorrow' => 'https://tianqi.2345.com/shangyou2d/70483.htm',
        ],
        'chongyi' => [
            'name'      => '崇义',
            'moji'      => 'https://tianqi.moji.com/fish/china/jiangxi/chongyi-county',
            'moji_wind' => 'https://tianqi.moji.com/weather/china/jiangxi/chongyi-county',
            'pressure_today' => 'https://tianqi.2345.com/chongyi1d/70466.htm',
            'pressure_tomorrow' => 'https://tianqi.2345.com/chongyi2d/70466.htm',
        ],
        'dayu' => [
            'name'      => '大余',
            'moji'      => 'https://tianqi.moji.com/fish/china/jiangxi/dayu-county',
            'moji_wind' => 'https://tianqi.moji.com/weather/china/jiangxi/dayu-county',
            'pressure_today' => 'https://tianqi.2345.com/dayu1d/70467.htm',
            'pressure_tomorrow' => 'https://tianqi.2345.com/dayu2d/70467.htm',
        ],
        'longnan' => [
            'name'      => '龙南',
            'moji'      => 'https://tianqi.moji.com/fish/china/jiangxi/longnan-city',
            'moji_wind' => 'https://tianqi.moji.com/weather/china/jiangxi/longnan-city',
            'pressure_today' => 'https://tianqi.2345.com/longnan1d/60503.htm',
            'pressure_tomorrow' => 'https://tianqi.2345.com/longnan2d/60503.htm',
        ],
        'dingnan' => [
            'name'      => '定南',
            'moji'      => 'https://tianqi.moji.com/fish/china/jiangxi/dingnan-county',
            'moji_wind' => 'https://tianqi.moji.com/weather/china/jiangxi/dingnan-county',
            'pressure_today' => 'https://tianqi.2345.com/dingnan1d/70469.htm',
            'pressure_tomorrow' => 'https://tianqi.2345.com/dingnan2d/70469.htm',
        ],
        'quannan' => [
            'name'      => '全南',
            'moji'      => 'https://tianqi.moji.com/fish/china/jiangxi/quannan-county',
            'moji_wind' => 'https://tianqi.moji.com/weather/china/jiangxi/quannan-county',
            'pressure_today' => 'https://tianqi.2345.com/quannan1d/60505.htm',
            'pressure_tomorrow' => 'https://tianqi.2345.com/quannan2d/60505.htm',
        ],
        'xingguo' => [
            'name'      => '兴国',
            'moji'      => 'https://tianqi.moji.com/fish/china/jiangxi/xingguo-county',
            'moji_wind' => 'https://tianqi.moji.com/weather/china/jiangxi/xingguo-county',
            'pressure_today' => 'https://tianqi.2345.com/xingguo1d/60906.htm',
            'pressure_tomorrow' => 'https://tianqi.2345.com/xingguo2d/60906.htm',
        ],
        'ruijin' => [
            'name'      => '瑞金',
            'moji'      => 'https://tianqi.moji.com/fish/china/jiangxi/ruijin',
            'moji_wind' => 'https://tianqi.moji.com/weather/china/jiangxi/ruijin',
            'pressure_today' => 'https://tianqi.2345.com/ruijin1d/60070.htm',
            'pressure_tomorrow' => 'https://tianqi.2345.com/ruijin2d/60070.htm',
        ],
        'huichang' => [
            'name'      => '会昌',
            'moji'      => 'https://tianqi.moji.com/fish/china/jiangxi/huichang-county',
            'moji_wind' => 'https://tianqi.moji.com/weather/china/jiangxi/huichang-county',
            'pressure_today' => 'https://tianqi.2345.com/huichang1d/61035.htm',
            'pressure_tomorrow' => 'https://tianqi.2345.com/huichang2d/61035.htm',
        ],
        'xunwu' => [
            'name'      => '寻乌',
            'moji'      => 'https://tianqi.moji.com/fish/china/jiangxi/xunwu-county',
            'moji_wind' => 'https://tianqi.moji.com/weather/china/jiangxi/xunwu-county',
            'pressure_today' => 'https://tianqi.2345.com/xunwu1d/60859.htm',
            'pressure_tomorrow' => 'https://tianqi.2345.com/xunwu2d/60859.htm',
        ],
        'anyuan' => [
            'name'      => '安远',
            'moji'      => 'https://tianqi.moji.com/fish/china/jiangxi/anyuan-county',
            'moji_wind' => 'https://tianqi.moji.com/weather/china/jiangxi/anyuan-county',
            'pressure_today' => 'https://tianqi.2345.com/anyuan1d/70464.htm',
            'pressure_tomorrow' => 'https://tianqi.2345.com/anyuan2d/70464.htm',
        ],
        'shicheng' => [
            'name'      => '石城',
            'moji'      => 'https://tianqi.moji.com/fish/china/jiangxi/shicheng-county',
            'moji_wind' => 'https://tianqi.moji.com/weather/china/jiangxi/shicheng-county',
            'pressure_today' => 'https://tianqi.2345.com/shicheng1d/60860.htm',
            'pressure_tomorrow' => 'https://tianqi.2345.com/shicheng2d/60860.htm',
        ]
    ];


    /**
     * @param $cityCode
     * @return bool
     */
    public static function grab($cityCode)
    {
        $data = [];
        $data = self::moji($cityCode, $data);
        $data = self::mojiWind($cityCode, $data);
        $data = self::pressure($cityCode, $data);
        foreach ($data as $item) {

            $item['city'] = $cityCode;
            $item['city_name'] = Constants::$city[$cityCode];

            //评分
            $item['score'] = self::score($item);

            //气压
            if (!array_key_exists('pressure', $item)) {
                $item['pressure'] = '/';
            }

            //背景色
            $item['bg_color'] = 'warning';
            if (strpos($item['evaluate'],'不适宜') !== false) {
                $item['bg_color'] = 'danger';
            } else if (strpos($item['evaluate'], '较适宜') !== false) {
                if ($item >= 73) {
                    //不低于73分为适宜钓鱼
                    $item['bg_color'] = 'success';
                    $item['evaluate'] = '适宜钓鱼';
                } else {
                    $item['bg_color'] = 'warning';
                }
            }

            //更新或写入
            if (Weather::where(['city' => $cityCode, 'date' => $item['date']])->exists()) {
                Weather::where(['city' => $cityCode, 'date' => $item['date']])->update($item);
            } else {
                Weather::create($item);
            }
        }
        return true;
    }


    public static function toDate($dayStr)
    {
        if ($dayStr == '今天') {
            return date('Y-m-d');
        }
        if ($dayStr == '明天') {
            return date('Y-m-d', strtotime('+ 1 day'));
        }
        if ($dayStr == '后天') {
            return date('Y-m-d', strtotime('+ 2 day'));
        }
        return '';
    }

    /**
     * 墨迹天气，钓鱼指数
     * @param $cityCode
     * @param $data
     * @return mixed
     */
    public static function moji($cityCode, $data)
    {
        $url = self::$city[$cityCode]['moji'];
        $content = file_get_contents($url);
        preg_match_all("/(<dl class=\"days clearfix\">).*?(<\/dl>)/is", $content,$regs);
        foreach ($regs[0] as $v) {
            preg_match_all("/[\x{4e00}-\x{9fa5}]+/u", $v,$info);
            $info = $info[0];

            //温度
            preg_match("/(<dd class=\"aqi_ftemp\">).*?(<\/dd>)/is", $v,$temperature);
            $temperature = str_replace(['<dd class="aqi_ftemp">', '</dd>'], '', $temperature[0]);

            //建议
            preg_match("/(<p>).*?(<\/p>)/is", $v,$proposal);
            $proposal = str_replace(['<p>', '</p>'], '', $proposal[0]);

            //日期
            $date = self::toDate($info[0]);
            $item = [
                'date' => $date,  //日期
                'weather' => $info[1],              //天气
                'temperature' => $temperature,      //温度
                'evaluate' => $info[4],             //评语
                'proposal' => $proposal,             //建议
            ];
            if (!array_key_exists($date, $data)) {
                $data[$date] = [];
            }
            $data[$date] = array_merge($data[$date], $item);
        }
        return $data;
    }


    /**
     * 墨迹天气，风向风力
     * @param $cityCode
     * @param $data
     * @return mixed
     */
    public static function mojiWind($cityCode, $data)
    {
        $url = self::$city[$cityCode]['moji_wind'];
        $content = file_get_contents($url);

        preg_match_all("/(<ul class=\"days clearfix\">).*?(<\/ul>)/is", $content,$regs);
        foreach ($regs[0] as $v) {
            preg_match_all("/[\x{4e00}-\x{9fa5}]+/u", $v,$info);
            $info = $info[0];

            //风力
            preg_match("/(<b>).*?(<\/b>)/is", $v,$windPower);
            $windPower = str_replace(['<b>', '</b>'], '', $windPower[0]);

            //日期
            $date = self::toDate($info[0]);
            $item = [
                'wind_direction' => $info[3],      //风向
                'wind_power' => $windPower,        //风力
            ];
            if (!array_key_exists($date, $data)) {
                $data[$date] = [];
            }
            $data[$date] = array_merge($data[$date], $item);
        }
        return $data;
    }

    /**
     * 气压
     * @param $cityCode
     * @param $data
     * @return mixed
     */
    public static function pressure($cityCode, $data)
    {
        //今天
        $url = self::$city[$cityCode]['pressure_today'];
        $content = file_get_contents("compress.zlib://" . $url);
        $content = iconv("gb2312", "utf-8//IGNORE", $content);
        preg_match("/(姘&nbsp;).*?(<\/span>)/is", $content,$regs);
        $pressure = str_replace([$regs[1], $regs[2]], '', $regs[0]);

        $today = date('Y-m-d');
        if (!array_key_exists($today, $data)) {
            $data[$today] = [];
        }
        $data[$today]['pressure'] = $pressure;

        //明天
        $url = self::$city[$cityCode]['pressure_tomorrow'];
        $content = file_get_contents("compress.zlib://" . $url);
        $content = iconv("gb2312", "utf-8//IGNORE", $content);
        preg_match("/(姘&nbsp;).*?(<\/span>)/is", $content,$regs);
        $pressure = str_replace([$regs[1], $regs[2]], '', $regs[0]);

        $tomorrow = date('Y-m-d', strtotime('+ 1 day'));
        if (!array_key_exists($tomorrow, $data)) {
            $data[$tomorrow] = [];
        }
        $data[$tomorrow]['pressure'] = $pressure;
        return $data;
    }

    /**
     * 计算分值
     * @param $data
     * @return int|mixed
     */
    protected static function score($data)
    {
        //起步分值
        $level = [
            '不适宜钓鱼' => 43,
            '较适宜钓鱼' => 68,
            '适宜钓鱼' => 73,
        ];
        //风力加分
        $wind = [
            0 => 15,
            1 => 11,
            2 => 8,
            3 => 4,
            4 => 3,
            5 => 0,
            6 => 0,
        ];
        //气压加分
        $pressure = [
            1050 => 15,
            1030 => 11,
            1010 => 6,
            990 => 4,
            980 => 0,
            970 => 0,
            950 => 0,
        ];

        $levelScore = array_key_exists($data['evaluate'], $level) ? $level[$data['evaluate']] : 60;
        $windScore = array_key_exists($data['wind_power'][0], $wind) ? $wind[$data['wind_power'][0]] : 0;
        $pressureScore = 0;
        if (array_key_exists('pressure', $data)) {
            $p = str_replace('hpa', '', $data['pressure']);
            foreach ($pressure as $k => $v) {
                if ($p >= $k) {
                    $pressureScore = $v;
                }
            }
        }
        $res = $levelScore + $windScore + $pressureScore;
        return $res + rand(-2, 2);
    }

}